Chapter 5 Optimizing Program Performance
#CSAPP
程序的正确性是首要的,在
- 可读性
- 实现难度、可维护性
- 运行效率
- 可移植性
- 效率、可移植性的需求
之间需要进行权衡
优化一个程序的步骤
- 优化算法、数据结构
- 除去编程语言层面的 redundency、unnecessasity
- 为目标机器建模
- 在模型上实现访存优化(cache, register 的从分利用)、指令级别的并行(充分利用计算硬件),分支预测优化,SIMD 向量化等
- 基准测试,profiling
主要的实现方式是利用编译器而不是直接手写汇编,所以需要十分了解编译器的优化行为
用 CPE 来衡量一个循环的执行效率
书中以数组的组合函数遍历的循环为例,展示了优化循环的方法:
-
基本优化
- Eliminating loop inefficiency
- Reducing procedure calls
- Eliminating unneeded memory reference
-
底层的指令并行优化
- 现代处理器的 execute 阶段的 out of order execution 和 superscalar 机制,functional unit 的 latency issue capacity,建立寄存器之间的数据依赖关系并分析 critical path(loop/readonly/writeonly/)
- loop unrolling, along with multiple accumulator / reassociation transformation,分析执行效率
- data transfer instead of control transfer
some limiting factors
- register spilling, unrolling layers > register file storage
- branch misprediction
- load / store functional unit 的机制(缓存处理),速度,write/use hazard
profiling